﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Media;

namespace CletcWeb
{
    public partial class bbs_mulu_view : System.Web.UI.Page
    {
        protected string menu2_id, title_id, thistitle;
        protected string titlename;

        protected void Page_Load(object sender, System.EventArgs e)
        {
            //if (!IsPostBack)
            //    ssConfig();

            Conn conn = new Conn();
            title_id = Request.Params["title_id"];
            thistitle = Request.Params["thistitle"];
            menu2_id = Request.Params["menu2_id"];
            tbtitleid.Text = title_id;
            tbtopic.Text = menu2_id;
            tbthistitle.Text = thistitle;

            string uname1 = Session["username1"].ToString();
            if (!IsPostBack)
            {
                //Conn cc = new Conn();
                //string sql00 = "select chakan from xinxi where chakan like '%" + uname1 + ",%' and title_id=" + title_id;
                //if (cc.sqlFirst(sql00) == "0")
                //{
                //    string sql0 = "update xinxi set chakan=chakan + '" + uname1 + ",' where title_id=" + title_id;
                //    cc.Conn_Insert(sql0);
                //}
                //cc.Dispose();
            }
            string SelectSql = "select * from bbs where f_topic like '%" + menu2_id + "%' and  f_pos='" + title_id + "' or title_id=" + title_id + "order by f_date";

            DataSet ObjDataSet = conn.Conn_Send(SelectSql);

            string imgHead, imgTail;
            imgHead = "<img src=uploadimage" + "/";
            imgTail = "></img><br><br>";
            DataGrid2.DataSource = ObjDataSet.Tables["a"].DefaultView;
            DataGrid2.Visible = true;
            DataGrid2.DataBind();

            //********以下代码用来判断此课程的附件（课件）是否为media可播放的视频**************************
            bool mediaok = false; //为真表示全部为media可播放课件
            string count1 = conn.sqlFirst("select count(*) from ImgUpload as i,bbs as b where i.flag=2 and b.title_id>=" + thistitle + " and i.title_id=b.title_id and b.f_topic like '%" + menu2_id + "%'");
            string count2 = conn.sqlFirst("select count(*) from ImgUpload as i,bbs as b where i.flag=2 and b.title_id>=" + thistitle + " and i.title_id=b.title_id and b.f_topic like '%" + menu2_id + "%' and (f_filename like '%.wmv' or f_filename like '%.wma' or f_filename like '%.mp3' or f_filename like '%.asx')");
            if (count1 == count2)
                mediaok = true;
            else
                mediaok = false;
            //如果为真，media控件可见，并顺序播放当前节附件
            if (mediaok == true)
            {
                Media1.Visible = true;
                beginplay();
            }
            //**********************************

            for (int i = 0; i < DataGrid2.Items.Count; i++)
            {
                Label editer = (Label)DataGrid2.Items[i].FindControl("editer");
                Label writerLb = (Label)DataGrid2.Items[i].FindControl("writerLb");
                Label del2 = (Label)DataGrid2.Items[i].FindControl("del2");
                Label LaName1 = (Label)DataGrid2.Items[i].FindControl("LaName1");
                Label Label9 = (Label)DataGrid2.Items[i].FindControl("Label9");	//帖子内容
                Label Label6 = (Label)DataGrid2.Items[i].FindControl("Label6");	//帖子标题
                Label Updatetime_bbs = (Label)DataGrid2.Items[i].FindControl("Updatetime_bbs");	//修改时间
                Label Label8 = (Label)DataGrid2.Items[i].FindControl("Label8");	//创建时间
                Label lahuifu = (Label)DataGrid2.Items[i].FindControl("lahuifu");	//回复、创建小节
                Label lalayer = (Label)DataGrid2.Items[i].FindControl("lalayer");	//层级

                //层级=1表示为目录的章，只有章的才显示回复“新建一节”
                if (lalayer.Text == "1")
                    lahuifu.Visible = true;
                else
                    lahuifu.Visible = false;

                //修改时间、创建时间如果相同，则不显示修改时间
                if (Label8.Text == Updatetime_bbs.Text)
                    Updatetime_bbs.Visible = false;
                else
                {
                    Updatetime_bbs.Visible = true;
                    Updatetime_bbs.Text = "<br>此文章修改于：" + Updatetime_bbs.Text;
                }

                //帖子的标题、内容用HTML方式显示
                Label9.Text = Server.HtmlDecode(Label9.Text);
                Label6.Text = Server.HtmlDecode(Label6.Text);

                //删除、编辑权限
                string role = Session["sRole"].ToString();
                string uname = conn.sqlFirst("select f_writer from bbs where title_id=" + title_id);
                if ((role == "管理员") | (uname == Session["username"].ToString()) | (Session["sconfirm"].ToString() == "审核未通过") | (Session["sconfirm"].ToString() == "新建"))
                {
                    editer.Visible = true;
                    del2.Visible = true;
                }
                if (role=="学员")
                {
                    lahuifu.Visible = false;
                }

                Label t2 = (Label)DataGrid2.Items[i].FindControl("t2");
                //查找图片\附件
                string imgSql = "select f_filename,f_remark,flag,f_truename,f_width,f_height from ImgUpload where title_id=" + t2.Text;
                SqlConnection MyConnection = new SqlConnection(conn.strProvider);
                SqlCommand myCommand = new SqlCommand(imgSql, MyConnection);
                MyConnection.Open();
                SqlDataReader reader2 = myCommand.ExecuteReader();
                //图片个数
                string imgCountSql = "select count(*) from ImgUpload where title_id=" + title_id;
                SqlConnection MyConnection3 = new SqlConnection(conn.strProvider);
                SqlCommand myCommand3 = new SqlCommand(imgCountSql, MyConnection3);
                MyConnection3.Open();
                SqlDataReader reader3 = myCommand3.ExecuteReader();
                reader3.Read();
                int imgCount = (Int32)reader3.GetValue(0);

                Label Label10 = (Label)DataGrid2.Items[i].FindControl("Label10");		//图片
                Label10.Text = null;
                Label LaDoc2 = (Label)DataGrid2.Items[i].FindControl("LaDoc2");//附件
                System.Web.UI.SilverlightControls.MediaPlayer media2 = (System.Web.UI.SilverlightControls.MediaPlayer)DataGrid2.Items[i].FindControl("media2");//media附件
                //ScriptManager ScriptManager2 = (ScriptManager)DataGrid2.Items[i].FindControl("ScriptManager2");
                string path = Server.MapPath("uploadimage") + "\\";//文件的路径
                int count = 1;
                while (reader2.Read())
                {
                    if (reader2.GetValue(2).ToString() == "1")
                    {
                        if (Int32.Parse(reader2.GetString(4).ToString()) > 600)
                            imgHead = "<img width=600 src=uploadimage" + "/";
                        Label10.Text += "<br><br>" + imgHead + reader2.GetValue(0).ToString() + imgTail + "<font size=2>" + reader2.GetValue(1).ToString() + "</font>";
                    }
                    else if ((reader2.GetValue(2).ToString() == "2") & (mediaok == false))
                    {
                        //这个地方的程序是判断文件类型，附件是media能播放的(.wmv .wma .mp3 .asx)，要显示media，否则显示ladoc2.
                        string fujianfile = reader2.GetValue(0).ToString();
                        int fujianzhui = fujianfile.IndexOf(".");
                        fujianfile = fujianfile.Substring(fujianzhui + 1);
                        if ((fujianfile == "wmv") | (fujianfile == "wma") | (fujianfile == "mp3") | (fujianfile == "asx"))
                        {
                            LaDoc2.Visible = false;
                            media2.Visible = true;
                            media2.MediaSource = reader2.GetValue(0).ToString();
                            //Response.Write("<script>alert("+media2.MediaSkinSource+");</script>");
                        }
                        else
                        {
                            LaDoc2.Visible = true;
                            media2.Visible = false;
                            LaDoc2.Text += "<object classid='clsid:D27CDB6E-AE6D-11CF-96B8-444553540000' id='obj1' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0' border='0' width='530' height='400'>" +
                            "<param name='movie' value='" + reader2.GetValue(0).ToString() + "'>" +
                            "<param name='quality' value='High'>" +
                            "<embed src='" + reader2.GetValue(0).ToString() + "' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' name='obj1' width='530' height='400'></object>";
                        }
                        count = count + 1;
                    }
                }
                if (mediaok == true)
                {
                    LaDoc2.Visible = false;
                    media2.Visible = false;
                }
                reader2.Close();
                reader3.Close();
                MyConnection3.Close();
                MyConnection.Close();
            }
            if (!Page.IsPostBack)
            {
                //标题表的阅读数＋1
                string UpSql = "UPDATE bbs SET f_read = f_read + 1 WHERE title_id =" + title_id;
                conn.Conn_Insert(UpSql);
            }
            conn.Dispose();
        }

        protected void beginplay()  //开始播放
        {
            setasx("0");   //首先生成播放列表
            //Media1.MediaUrl = "~/video/" + Session["sUserName"].ToString() + ".asx";
            Media1.MediaUrl = Session["sUserName"].ToString() + ".asx";
            //Response.Write("<script>alert(" + Media1.MediaUrl + ");</script>");

            //m_player.newMedia("你的URL").GetDuration();直接获得时间
        }

        protected void setasx(string ptitle_id)
        {
            //
            SqlConnection MyConnection = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["gConnectionString"]);
            //string zsql = "select f_filename,title_id from vw_bbs_imgupload where f_topic='" + Session["stopic"].ToString() + "/' order by f_date1";
            string zsql = "select i.f_filename,b.title_id from ImgUpload as i,bbs as b where i.flag=2 and b.title_id>=" + tbthistitle.Text + " and i.title_id=b.title_id and b.f_topic like '%" + tbtopic.Text + "%' order by f_date1";
            SqlCommand myCommand = new SqlCommand(zsql, MyConnection);
            MyConnection.Open();

            SqlDataReader zReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            string zcontent;
            zcontent = "<ASX version = \"3.0\">";
            //zcontent += "<TITLE>07baby.com video course</TITLE>";
            //bool zbegin;
            //if (ptitle_id == "0") //系统约定：当从头开始播放时，参数ptitle_id=“0”
            //    zbegin = true;
            //else
            //    zbegin = false;
            while (zReader.Read())
            {
                //if (zReader.GetInt64(1).ToString().Trim() == ptitle_id)
                //    zbegin = true;
                //if (zbegin)
                //{
                zcontent += "<ENTRY>";
                //zcontent += "<TITLE>07baby</TITLE>";
                //zcontent += "<AUTHOR>07baby</AUTHOR>";
                //zcontent += "<COPYRIGHT>07baby.com</COPYRIGHT>";
                zcontent += "<REF HREF = \"" + zReader.GetValue(0).ToString() + "\" />";
                zcontent += "</ENTRY>";
                //}
            }
            zcontent += "</ASX>";
            zReader.Close();
            myCommand.Dispose();
            MyConnection.Close();
            //string zpathname = Server.MapPath("~/video/");
            string zpathname = Server.MapPath("~/bbs/uploadimage/");
            string zfilename = Session["sUserName"].ToString() + ".asx";
            create_file(zpathname, zfilename, zcontent);
        }
        protected void create_file(string pathname, string filename, string filecontent)
        {
            DirectoryInfo di = new DirectoryInfo(pathname);
            di.Create();

            string fileurl = pathname + filename;

            FileInfo fi = new FileInfo(fileurl);
            //也可以用FileStream fs = new FileStream(FileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
            //其中不用CreateNew，而是用Create，因为前者当文件已经存在时会提示出错，而后者这时先删除文件，然后新建一个
            //最后简化为：FileStream fs = new FileStream(FileName, FileMode.Create);
            //参见http://www.cnblogs.com/yank/archive/2007/11/16/961878.html
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fileurl);
            sw.WriteLine(filecontent);
            sw.Flush();
            sw.Close();
        }
    }
}